<template>
  <div class="score-analysis-container">
    <!-- 筛选条件区域 -->
    <div class="filter-section">
      <el-select 
        v-model="queryParams.semester" 
        placeholder="开课学期"
        class="filter-item"
        @change="initCourse"
        clearable
      >
        <el-option 
          v-for="(semester,index) in availableSemesters" 
          :key="index" 
          :value="semester"
          :label="semester"
        />
      </el-select>
      <el-select
        filterable
        v-model="queryP.selectCourseId"
        placeholder="课程"
        class="filter-item"
        @change="initClass"
        clearable
      >
        <el-option
          v-for="(item, index) in courseList"
          :key="index"
          :label="item.courseName"
          :value="item.subId"
        />
      </el-select>
      <el-select
        filterable
        v-model="queryP.selectClassId"
        placeholder="班级"
        class="filter-item"
        @change="fetchData"
        clearable
      >
        <el-option
          v-for="(item, index) in classList"
          :key="index"
          :label="item.className"
          :value="item.classId"
        />
      </el-select>
      <el-select
        v-model="scoreDiff"
        placeholder="分差阈值"
        class="filter-item"
        @change="fetchData"
        clearable
      >
        <el-option
          v-for="(item, index) in scoreDiffList"
          :key="index"
          :label="`≥${item.score}分`"
          :value="item.score"
        />
      </el-select>
    </div>

    <!-- 图表区域 -->
    <div class="chart-section">
      <div ref="chart" class="echarts-container"></div>
    </div>

<!-- 异常数据区域 -->
    <div class="abnormal-section">
      <h4 class="section-title">异常分差数据（分差≥{{ scoreDiff }}分）</h4>
      <el-table
        :data="abnormalData"
        class="data-table"
        stripe
        border
        highlight-current-row
        @row-click="handleRowClick"
      >

      <el-table-column prop="subId" label="课程ID" width="120"></el-table-column>
      <el-table-column prop="studentId" label="学生ID" width="120"></el-table-column>
      <el-table-column prop="dayScore" label="平时成绩" align="center"></el-table-column>
      <el-table-column prop="score" label="期末成绩" align="center"></el-table-column>
      <el-table-column prop="gap" label="分差" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.gap > 30 ? 'danger' : 'warning'">
            {{ scope.row.gap }}
          </el-tag>
        </template>
      </el-table-column>
      <template slot="empty">
        <div class="empty-tip">
          <i class="el-icon-info"></i>
          <span>当前筛选条件下无异常数据</span>
        </div>
      </template>
      </el-table>
    </div>

    <!-- 对话框 -->
    <el-dialog
      :title="`${selectedStudent.studentName} 的成绩详情`"
      :visible.sync="detailDialogVisible"
      width="680px"
      custom-class="detail-dialog"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="学号">{{ selectedStudent.studentId }}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{ selectedStudent.studentName }}</el-descriptions-item>
        <el-descriptions-item label="班级">{{ selectedStudent.className }}</el-descriptions-item>
        <el-descriptions-item label="课程">{{ selectedStudent.courseName }}</el-descriptions-item>
        <el-descriptions-item label="总成绩" :span="2">
          <el-tag :type="selectedStudent.sumScore >= 60 ? 'success' : 'danger'">
            {{ selectedStudent.sumScore }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="期中成绩">
          {{ selectedStudent.halfScore || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="实验成绩">
          {{ selectedStudent.experScore || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="期末成绩">
          <el-tag type="warning">{{ selectedStudent.score }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="平时成绩" :span="2">
          <el-tag type="info">{{ selectedStudent.dayScore }}</el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { getDev,getCourse,getClass } from '@/api/student';
import { getSemester } from '@/api/dashboard';

export default {
  data() {
    return {
      // 新增对话框相关数据
      detailDialogVisible: false,
      availableSemesters: [],
      selectedStudent: {
        studentId: '',
        studentName: '',
        className: '',
        courseName: '',
        dayScore: 0,
        halfScore: 0,
        experScore: 0,
        score: 0,
        sumScore: 0
      },
      scoreDiffList:[
        {
          score:10
        },
        {
          score:15
        },
        {
          score:20
        },
        {
          score:25
        },
        {
          score:30
        },
    ],
      scoreDiff: 10,
      chart: null,
      abnormalData: [],
      courseList:[],//课程列表
      classList:[],//选择的课程id
      rawData:[],
      queryP:{
        selectClassId:'',
        selectCourseId:'',
      },
      queryParams:{
        pageNum:1,
        pageSize:50,
      },

    };
  },
  computed: {
    // 处理后的图表数据
    chartData() {
      return this.rawData.map(item => ({
        ...item,
        gap: Math.abs(item.dayScore - item.score).toFixed(2)
      }));
    }
  },
  mounted() {
    this.select();
  },
  methods: {
    initCourse(semester){
      getCourse(semester).then(res=>{
            this.courseList=res.data;
          })
    },
    // 新增行点击处理方法
    handleRowClick(row) {
      this.selectedStudent = {
        studentId: row.studentId,
        studentName: row.studentName || '未记录', // 处理可能的空值
        className: row.className || '未知班级',
        courseName: row.courseName, // 根据课程ID获取课程名称
        dayScore: row.dayScore,
        halfScore: row.halfScore,
        experScore: row.experScore,
        score: row.score,
        sumScore: row.sumScore // 计算总成绩
      };
      this.detailDialogVisible = true;
    },
    // 获取后端数据
    select(){
      getSemester().then(res=>{
        this.availableSemesters=res.data
      })
      getCourse().then(res=>{
        console.log(res.data);
        this.courseList=res.data;
      })
    },
    initClass(courseId){
      getClass(courseId).then(res => {
        this.classList=res.data;
      })
    },
    async fetchData() {
      try {       
        this.loading = true; // 添加加载状态 
        const res = await getDev(this.queryP); // 直接 await
        console.log('API响应数据:', res.data);
        // 确保数据结构正确
        if (res && res.data) {
          this.rawData = res.data;
          this.initChart();
          this.detectAbnormal();
        } else {
          throw new Error('响应数据格式错误');
        }
      } catch (error) {
        console.error('数据加载失败:', error);
      } finally {
        this.loading = false;
      }
    },
    // 初始化散点图
    initChart() {
      this.chart = echarts.init(this.$refs.chart);
      const option = {
        title: {
          text: '平时成绩 vs 期末成绩分析',
          left: 'center'
        },
        tooltip: {
          formatter: params => `
            <strong>${params.data.studentId}</strong><br/>
            课程：${params.data.subId}<br/>
            平时：${params.data.dayScore}<br/>
            期末：${params.data.score}<br/>
            分差：<span style="color:${params.color}">${params.data.gap}</span>
          `
        },
        xAxis: {
          name: '平时成绩',
          min: 0,
          max: 100
        },
        yAxis: {
          name: '期末成绩',
          min: 0,
          max: 100
        },
        series: [{
          type: 'scatter',
          data: this.chartData.map(d => ({
            value: [d.dayScore, d.score],
            itemStyle: {
              color: d.gap > this.scoreDiff ? '#ff4d4f' : '#1890ff' //分差阈值30  
            },
            ...d
          })),
          symbolSize: 10
        }, {
          type: 'line', // 参考线 y=x
          data: [[0, 0], [100, 100]],
          silent: true,
          lineStyle: {
            color: '#999',
            type: 'dashed'
          }
        }]
      };
      this.chart.setOption(option);
    },

    // 检测异常数据（分差>30）
    detectAbnormal() {
      this.abnormalData = this.chartData
        .filter(d => d.gap > this.scoreDiff)
        .sort((a, b) => b.gap - a.gap);
    }
  }
};
</script>
<style scoped>
/* 容器整体布局 */
.score-analysis-container {
  padding: 20px;
  background-color: #f5f7fa;
}

/* 筛选条件区域 */
.filter-section {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  margin-bottom: 20px;
}
.filter-item {
  width: 220px;
}
.filter-item::v-deep .el-input__inner {
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

/* 图表容器 */
.chart-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
  margin-bottom: 24px;
}
.echarts-container {
  width: 100%;
  height: 500px; /* 适当降低高度 */
}

/* 异常数据区域 */
.abnormal-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
}
.section-title {
  color: #606266;
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 500;
}

/* 表格样式 */
.data-table::v-deep .el-table__header th {
  background-color: #f8f9fa;
  font-weight: 600;
}
.data-table::v-deep .el-table__row:hover {
  cursor: pointer;
  background-color: #f5f7fa !important;
}

/* 对话框样式 */
.detail-dialog::v-deep .el-dialog__header {
  border-bottom: 1px solid #ebeef5;
}
.detail-dialog::v-deep .el-descriptions-item__label {
  color: #909399;
  width: 100px;
}
.empty-tip {
  padding: 20px;
  color: #909399;
  text-align: center;
}
</style>
